﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace BlockingCollection
{
    class Program
    {
        static void Main(string[] args)
        {
            Test1();
        }


        private static async void Test2()
        {
            var list = new BlockingCollection<int>();

            var tasks = new List<Task>();

            for (int i = 0; i < 100; i++)
            {
                int value = i;
                var task = Task.Run(async () =>
                  {
                      await Task.Delay(500);

                      list.Add(value);

                  });

                tasks.Add(task);
            }

            await Task.WhenAll(tasks);

            Console.WriteLine($"list {list.Count}");

            Console.ReadKey();
        }


        private static void Test1()
        {
            var bcollec = new BlockingCollection<int>(5);
            //试图添加1-50
            Task.Run(() =>
            {
                Parallel.For(1, 51, i =>
                {
                    Console.WriteLine("准备加入：" + i);
                    bcollec.Add(i);
                    Console.WriteLine("== 成功加入：" + i);
                    Thread.Sleep(1000);
                });
            });

            //等待一小段时间后马上调用CompleteAdding
            Thread.Sleep(500);
            Console.WriteLine("调用CompleteAdding");
            bcollec.CompleteAdding();

            Thread.Sleep(Timeout.Infinite);
        }
    }
}
